package com.stonedt.spider.util;

import org.springframework.stereotype.Component;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author 康涵博
 * @Description 把对应的相对路径都改为绝对路径并替换(替换之前做个判断是否为绝对路径)
 * @Date 19:01 2024/4/19
 * @Param
 * @return
 */
@Component
public class ReturnHtmlUtil {

    public static String processHtml(String html,String baseUrl) {
        try {
            StringBuffer sb = new StringBuffer();
            try {
                //识别“//”开头的路径，如果有，直接替换成相应字符
                html = html.replaceAll("src=\"//", "src=\"http://");
                html = html.replaceAll("href=\"//", "href=\"http://");
                html = html.replaceAll("href=\" /", "href=\"/");
                // 匹配CSS资源（）包括解析之后URl后边带空格会导致转换出异常的
//                Pattern cssPattern = Pattern.compile("href=\"([^\"]+\\.css)(?=\\s|$)");
                //匹配css资源解析之后.css后不带空格的路径，如果解析后的代码有空格会报错
                Pattern cssPattern = Pattern.compile("href=\"([^\"]+\\.css)");
                Matcher cssMatcher = cssPattern.matcher(html);
                sb = new StringBuffer();
                while (cssMatcher.find()) {
                    if(cssMatcher.group(1).startsWith("//")){
                        continue;
                    }
                    //System.out.println("CSS Resource: " + cssMatcher.group(1));
                    //将相对转绝对
                    URL absoluteUrl = convertToAbsoluteUrl(baseUrl, cssMatcher.group(1));
                    //转换后替换
                    cssMatcher.appendReplacement(sb, "href=\"" + absoluteUrl + "\"");
                }
                // 将剩余的HTML内容添加到StringBuffer中
                cssMatcher.appendTail(sb);
//            // 将StringBuffer转换为字符串
                html = sb.toString();
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }

            try {
                // 匹配JS资源
                //用于匹配。js结尾的地址
//                Pattern jsPattern = Pattern.compile("src=\"([^\"]+\\.js).*\"");
                //用于匹配.js后跟着其他字符串的地址
                Pattern jsPattern = Pattern.compile("src=\"([^\"]+\\.js)\"");
                Matcher jsMatcher = jsPattern.matcher(html);
                sb = new StringBuffer();
                while (jsMatcher.find()) {
                   // System.out.println("JS Resource: " + jsMatcher.group(1));
                    URL absoluteUrl = convertToAbsoluteUrl(baseUrl, jsMatcher.group(1));
                    //转换后替换
                    jsMatcher.appendReplacement(sb, "src=\"" + absoluteUrl + "\"");
                }
                jsMatcher.appendTail(sb);
                html = sb.toString();
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }

            try {
                // 匹配IMG资源
                Pattern imgPattern = Pattern.compile("src=\"([^\"]+\\.(jpg|jpeg|gif|png))\"");
//                Pattern imgPattern = Pattern.compile("src=\"(.*?)\"");
                Matcher imgMatcher = imgPattern.matcher(html);
                sb = new StringBuffer();
                while (imgMatcher.find()) {
                    System.out.println("IMG Resource: " + imgMatcher.group(1));
                    URL absoluteUrl = convertToAbsoluteUrl(baseUrl, imgMatcher.group(1));
                    //转换后替换
                    imgMatcher.appendReplacement(sb, "src=\"" + absoluteUrl + "\"");
                }
                imgMatcher.appendTail(sb);
                html = sb.toString();
            } catch (URISyntaxException e) {
//                e.printStackTrace();
                throw new RuntimeException(e);
            }

            try {
                //匹配页面中Url包括解析之后URl前边带空格导致转换出异常的
                String regex = "href=\"\\s([^\"]*)\"";
                Pattern urlPattern = Pattern.compile(regex);
                Matcher urlMatcher = urlPattern.matcher(html);
                sb = new StringBuffer();
                while (urlMatcher.find()) {
                    if(urlMatcher.group(1).startsWith("//") || urlMatcher.group(1).startsWith("javascript:") || urlMatcher.group(1).startsWith("{{") || urlMatcher.group(1).endsWith(" ")){
                        continue;
                    }
                    System.out.println("URL Resource: " + urlMatcher.group(1));
                    URL absoluteUrl = convertToAbsoluteUrl(baseUrl, urlMatcher.group(1));
                    //转换后替换
                    urlMatcher.appendReplacement(sb, "href=\"" + absoluteUrl + "\"");
                }
                urlMatcher.appendTail(sb);
                html = sb.toString();
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);

            }
            System.out.println(html);
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
        return html;
    }

    /**
     * @Author 康涵博
     * @Description 相对转绝对路径转换URL对象
     * @Date 17:32 2024/4/23
     * @Param [java.lang.String, java.lang.String]
     * @return java.net.URL
     */
    public static URL convertToAbsoluteUrl(String baseUrl, String relativePath) throws URISyntaxException {
        // 将baseUrl字符串转换为URI对象
        URI baseUri = new URI(baseUrl);
        // 使用resolve方法将相对路径解析为绝对路径，得到一个新的URI对象
        URI absoluteUri = baseUri.resolve(relativePath);
        try {
            // 将绝对路径的URI对象转换为URL对象并打印输出
            System.out.println(absoluteUri.toURL());
            // 返回转换后的URL对象
            return absoluteUri.toURL();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
//            throw new RuntimeException(e);
            e.printStackTrace();
        }
        // 如果发生异常，返回null
        return null;
    }

}

